package com.bilgeadam.customtags;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author Bora SAYINER
 * @since Jan 18, 2015 5:30:24 PM
 * @version 1.0
 */
public class TableTag extends SimpleTagSupport {

	private List items;
	private String type;

	@Override
	public void doTag() throws JspException, IOException {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("<table class='pure-table'>");
		Class<?> clazz = null;
		try {
			clazz = Class.forName(type);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Method[] methods = clazz.getDeclaredMethods();
		stringBuffer.append("<thead>");
		stringBuffer.append("<tr>");
		{
			for (Method method : methods) {
				if (method.getName().startsWith("get")) {
					stringBuffer.append("<th>");
					if (method.getName().startsWith("get")) {
						stringBuffer.append(method.getName().substring(3));
					}
					stringBuffer.append("</th>");
				}
			}
		}
		stringBuffer.append("</tr>");
		stringBuffer.append("</thead>");
		stringBuffer.append("<tbody>");
		for (int i = 0; i < items.size(); i++) {

			if (i % 2 == 0) {
				stringBuffer.append("<tr>");
			} else {
				stringBuffer.append("<tr class='pure-table-odd'>");
			}

			for (Method method : methods) {
				if (method.getName().startsWith("get")) {
					try {
						Object obj = method.invoke(items.get(i), null);
						stringBuffer.append("<td>" + obj + "</td>");
					} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
			stringBuffer.append("</tr>");
		}
		stringBuffer.append("</tbody>");
		stringBuffer.append("</table>");
		getJspContext().getOut().print(stringBuffer.toString());
	}

	public List getItems() {
		return items;
	}

	public void setItems(List items) {
		this.items = items;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}
